package com.vibeplayer.app.util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;

import androidx.preference.PreferenceManager;

import com.vibeplayer.app.model.Song;

import java.util.ArrayList;
import java.util.List;

/**
 * 媒体扫描器，用于扫描设备上的音频文件
 */
public class MediaScanner {
    private static final String TAG = "MediaScanner";
    private Context context;
    private MediaContentObserver mediaContentObserver;
    private List<Song> cachedSongs; // 缓存扫描结果
    private boolean isObserverRegistered = false;
    private OnScanCompletedListener scanCompletedListener;
    
    // 定义监听器接口
    public interface OnScanCompletedListener {
        void onScanCompleted(List<Song> songs);
    }
    
    public MediaScanner(Context context) {
        this.context = context;
        this.mediaContentObserver = new MediaContentObserver(new Handler(Looper.getMainLooper()));
    }
    
    /**
     * 设置扫描完成监听器
     * @param listener 监听器
     */
    public void setScanCompletedListener(OnScanCompletedListener listener) {
        this.scanCompletedListener = listener;
    }
    
    /**
     * 注册媒体内容观察者，监听媒体库变化
     */
    public void registerMediaObserver() {
        if (!isObserverRegistered) {
            ContentResolver contentResolver = context.getContentResolver();
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            contentResolver.registerContentObserver(uri, true, mediaContentObserver);
            isObserverRegistered = true;
            Log.d(TAG, "Media content observer registered");
        }
    }
    
    /**
     * 注销媒体内容观察者
     */
    public void unregisterMediaObserver() {
        if (isObserverRegistered) {
            ContentResolver contentResolver = context.getContentResolver();
            contentResolver.unregisterContentObserver(mediaContentObserver);
            isObserverRegistered = false;
            Log.d(TAG, "Media content observer unregistered");
        }
    }
    
    /**
     * 自动扫描媒体库
     * 如果启用了自动扫描，则扫描设备上的所有音频文件
     */
    public void autoScanMedia() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean autoScanEnabled = prefs.getBoolean("auto_scan_enabled", true);
        
        if (autoScanEnabled) {
            Log.d(TAG, "Auto scan enabled, starting scan...");
            scanMediaAsync();
        } else {
            Log.d(TAG, "Auto scan disabled, skipping");
        }
    }
    
    /**
     * 异步扫描媒体库
     */
    public void scanMediaAsync() {
        new Thread(() -> {
            List<Song> songs = getAllSongs();
            
            // 更新缓存
            cachedSongs = songs;
            
            // 通知监听器
            if (scanCompletedListener != null) {
                new Handler(Looper.getMainLooper()).post(() -> 
                    scanCompletedListener.onScanCompleted(songs)
                );
            }
        }).start();
    }
    
    /**
     * 扫描设备上的所有音频文件
     * @return 歌曲列表
     */
    public List<Song> getAllSongs() {
        // 如果有缓存且不需要强制刷新，直接返回缓存
        if (cachedSongs != null && !shouldRefreshCache()) {
            Log.d(TAG, "Using cached songs list, size: " + cachedSongs.size());
            return new ArrayList<>(cachedSongs);
        }
        
        List<Song> songs = new ArrayList<>();
        
        ContentResolver contentResolver = context.getContentResolver();
        
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            uri = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
            Log.d(TAG, "Using MediaStore.VOLUME_EXTERNAL for Android 10+");
        } else {
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Log.d(TAG, "Using EXTERNAL_CONTENT_URI for pre-Android 10");
        }
        
        String[] projection = new String[]{
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media.MIME_TYPE  // 添加MIME_TYPE用于调试
        };
        
        // 移除所有过滤条件
        String selection = null;
        String[] selectionArgs = null;
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        
        Log.d(TAG, "Starting media scan with URI: " + uri);
        Log.d(TAG, "No selection criteria applied");
        
        try {
            Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
            
            if (cursor != null) {
                Log.d(TAG, "Cursor obtained, count: " + cursor.getCount());
                
                if (cursor.moveToFirst()) {
                    int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
                    int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                    int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                    int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
                    int pathColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                    int albumIdColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
                    int mimeTypeColumn = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE);
                    
                    Log.d(TAG, "Column indices - id:" + idColumn + ", title:" + titleColumn + 
                          ", artist:" + artistColumn + ", path:" + pathColumn);
                    
                    do {
                        try {
                            long id = cursor.getLong(idColumn);
                            String title = cursor.getString(titleColumn);
                            String artist = cursor.getString(artistColumn);
                            String album = cursor.getString(albumColumn);
                            long duration = cursor.getLong(durationColumn);
                            String path = cursor.getString(pathColumn);
                            long albumId = cursor.getLong(albumIdColumn);
                            String mimeType = cursor.getString(mimeTypeColumn);
                            
                            Song song = new Song(id, title, artist, album, path, duration, albumId);
                            songs.add(song);
                            Log.d(TAG, String.format("Found audio: title=%s, artist=%s, duration=%d, mime=%s, path=%s",
                                    title, artist, duration, mimeType, path));
                            
                        } catch (Exception e) {
                            Log.e(TAG, "Error processing cursor row", e);
                        }
                    } while (cursor.moveToNext());
                } else {
                    Log.w(TAG, "Cursor is empty");
                }
                
                cursor.close();
                Log.d(TAG, "Scan completed, found " + songs.size() + " songs");
            } else {
                Log.e(TAG, "Failed to obtain cursor");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error scanning media", e);
        }
        
        // 更新缓存和时间戳
        cachedSongs = new ArrayList<>(songs);
        updateCacheTimestamp();
        
        return songs;
    }
    
    /**
     * 判断是否应该刷新缓存
     * @return 是否需要刷新
     */
    private boolean shouldRefreshCache() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        long lastScanTime = prefs.getLong("last_scan_timestamp", 0);
        long cacheValidityPeriod = prefs.getInt("cache_validity_period", 3600) * 1000; // 默认1小时（毫秒）
        
        return System.currentTimeMillis() - lastScanTime > cacheValidityPeriod;
    }
    
    /**
     * 更新缓存时间戳
     */
    private void updateCacheTimestamp() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong("last_scan_timestamp", System.currentTimeMillis());
        editor.apply();
    }
    
    /**
     * 清除扫描缓存，强制下次扫描重新获取
     */
    public void clearCache() {
        cachedSongs = null;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong("last_scan_timestamp", 0);
        editor.apply();
        Log.d(TAG, "Cache cleared");
    }
    
    /**
     * 根据ID获取歌曲
     * @param songId 歌曲ID
     * @return 歌曲对象，如果未找到则返回null
     */
    public Song getSongById(long songId) {
        // 如果有缓存，先从缓存中查找
        if (cachedSongs != null) {
            for (Song song : cachedSongs) {
                if (song.getId() == songId) {
                    return song;
                }
            }
        }
        
        ContentResolver contentResolver = context.getContentResolver();
        
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media._ID + " = ?";
        String[] selectionArgs = new String[]{String.valueOf(songId)};
        
        Cursor cursor = contentResolver.query(uri, null, selection, selectionArgs, null);
        
        if (cursor != null && cursor.moveToFirst()) {
            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
            int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            int pathColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
            int albumIdColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
            
            long id = cursor.getLong(idColumn);
            String title = cursor.getString(titleColumn);
            String artist = cursor.getString(artistColumn);
            String album = cursor.getString(albumColumn);
            long duration = cursor.getLong(durationColumn);
            String path = cursor.getString(pathColumn);
            long albumId = cursor.getLong(albumIdColumn);
            
            cursor.close();
            
            return new Song(id, title, artist, album, path, duration, albumId);
        }
        
        if (cursor != null) {
            cursor.close();
        }
        
        return null;
    }
    
    /**
     * 根据ID列表获取歌曲列表
     * @param songIds 歌曲ID列表
     * @return 歌曲列表
     */
    public List<Song> getSongsByIds(List<Long> songIds) {
        List<Song> songs = new ArrayList<>();
        
        for (Long songId : songIds) {
            Song song = getSongById(songId);
            if (song != null) {
                songs.add(song);
            }
        }
        
        return songs;
    }
    
    /**
     * 获取专辑封面的URI
     * @param albumId 专辑ID
     * @return 专辑封面的URI
     */
    public Uri getAlbumArtUri(long albumId) {
        return ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
    }
    
    /**
     * 根据关键字搜索歌曲
     * @param query 搜索关键字
     * @return 匹配的歌曲列表
     */
    public List<Song> searchSongs(String query) {
        List<Song> songs = new ArrayList<>();
        
        ContentResolver contentResolver = context.getContentResolver();
        
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0 AND (" +
                MediaStore.Audio.Media.TITLE + " LIKE ? OR " +
                MediaStore.Audio.Media.ARTIST + " LIKE ? OR " +
                MediaStore.Audio.Media.ALBUM + " LIKE ?)";
        String[] selectionArgs = new String[]{"%" + query + "%", "%" + query + "%", "%" + query + "%"};
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        
        Cursor cursor = contentResolver.query(uri, null, selection, selectionArgs, sortOrder);
        
        if (cursor != null && cursor.moveToFirst()) {
            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
            int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            int pathColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
            int albumIdColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
            
            do {
                long id = cursor.getLong(idColumn);
                String title = cursor.getString(titleColumn);
                String artist = cursor.getString(artistColumn);
                String album = cursor.getString(albumColumn);
                long duration = cursor.getLong(durationColumn);
                String path = cursor.getString(pathColumn);
                long albumId = cursor.getLong(albumIdColumn);
                
                Song song = new Song(id, title, artist, album, path, duration, albumId);
                songs.add(song);
                
            } while (cursor.moveToNext());
            
            cursor.close();
        }
        
        return songs;
    }
    
    /**
     * 媒体内容观察者，监听媒体库变化
     */
    private class MediaContentObserver extends ContentObserver {
        public MediaContentObserver(Handler handler) {
            super(handler);
        }
        
        @Override
        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }
        
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            Log.d(TAG, "Media content changed, triggering auto scan");
            // 检测到媒体库变化，触发自动扫描
            autoScanMedia();
        }
    }
} 